from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import cgi, threading

irc = None

def init(bot):
    global irc
    irc = bot

    wa = WebAdminThread(irc=bot)
    wa.start()


class WebAdminThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, *args, **kwargs):
        threading.Thread.__init__(self, group, target, name, args, kwargs)
        self.irc = kwargs['irc']
        self.daemon = True

    def run(self):
        addr_info = ('', 8831)
        httpd = WebAdminServer(addr_info, WebAdminHandler)
        while True:
            if not self.irc.connected:
                break
            httpd.handle_request()

class WebAdminServer(ThreadingMixIn, HTTPServer):
    pass
    
class WebAdminHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address,
            server)

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        print self.path
        start = "webadmin"
        if self.path == "/":
            fn = start + "/admin.html"
        else:
            fn = start + self.path

        f = open(fn)
        self.wfile.write(f.read() + "\r\n\r\n")
        f.close()

    def do_POST(self):
        global irc
        self.cmd = self.path
        self.post = cgi.FieldStorage(fp=self.rfile, headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })

        self.processor = AdminCommandHandler(irc)
        self.processor.process(self.cmd, self.post)

        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("ok\r\n\r\n")

class AdminCommandHandler():

    def __init__(self, irc):
        self.irc = irc
    
    def process(self, cmd, data):
        mname = "cmd_" + cmd[1:]
        if not hasattr(self, mname):
            print "Sorry, I don't know '%s'" % mname
            return

        method = getattr(self, mname)
        return method(data)

    def cmd_say(self, params):
        self.irc.privmsg(params['target'].value, params['message'].value)

    def cmd_action(self, params):
        self.irc.action(params['target'].value, params['message'].value)

    def cmd_quit(self, params):
        self.irc.terminate(params['message'].value)

    def cmd_load(self, params):
        p = params['target'].value
        self.irc.load_plugin(p)
        print "** Will load plugin: %s" % params['target'].value

    def cmd_unload(self, params):
        p = params['target'].value
        self.irc.unload_plugin(p)
        print "** Will unload plugin: %s" % params['target'].value

    def cmd_rehash(self, params):
        p = params['target'].value
        self.irc.rehash_plugin(p)
        print "** Will rehash plugin: %s" % params['target'].value

    def cmd_join(self, params):
        ch = params['target'].value
        self.irc.joinc(ch)


#if __name__ == "__main__":
#    addr_info = ('', 8831)
#    httpd = HTTPServer(addr_info, WebAdminHandler)
#    try:
#        httpd.serve_forever()
#    except KeyboardInterrupt:
#        pass
#    httpd.server_close()
